function MosMom = MosMomGen(ts,OptMJD)
%MosMomGen - Generation of an offsets matrix (mom notation) 
%
%   MosMom = MosMomGen(tsDataIn,OptMJD)
%
% This function provides the offsets matrix with mom notation MosMom
% from the tsData object tsDataIn.
% If no offsest are in tsDataIn, MosMom = [] is returned.
% If OptMJD is undefined, empty or false, dates in MosMom are as in 
% tsDataIn, i.e. are in MATLAB serial form (note that in this case a 
% serial-to-MJD conversion is required before the use of the returned 
% MosMom matrix in those cases where the MJD is required). 
% If OptMJD is true, dates in MosMom are in MJD form.

% G. Teza, 2022

if (nargin < 2) || isempty(OptMJD)
    OptMJD = 0;
end
OptMJD = logical(OptMJD);

oE = ts.offsetsE;
oN = ts.offsetsN;
oV = ts.offsetsV;

if isempty(oE) && isempty(oN) && isempty(oV)
    MosMom = [];
    return
end

if OptMJD
    oE = round(serial2MJD(oE(:)));
    oN = round(serial2MJD(oN(:)));
    oV = round(serial2MJD(oV(:)));
else
    oE = round(oE(:));
    oN = round(oN(:));
    oV = round(oV(:));
end

oENV = [[oE zeros(size(oE))]; [oN ones(size(oN))]; [oV 2*ones(size(oV))]];
oENV1 = oENV(:,1);
[~,IS] = sort(oENV1);
oENV = oENV(IS,:);  % now it is completely sorted
nENV = size(oENV,1);
oENV = [oENV zeros(nENV,1) ones(nENV,1)]; % 4-th col for the final multiple row deletion

for k = 1:nENV
    ok = oENV(k,1);
    ck = oENV(k,2);
    Isk = (oENV(:,1) == ok) & (oENV(:,4) == 1); 
    ndk = sum(Isk);
    if ndk == 1
        if ck == 0
            oENV(k,3) = 4;
        elseif ck == 1
            oENV(k,3) = 2;
        else
            oENV(k,3) = 1;
        end
    elseif ndk == 2
        ck2 = oENV(Isk,2);
        ck2 = ck2(2);
        if (ck == 0) && (ck2 == 1)
            oENV(k,3) = 6;
        elseif (ck == 0) && (ck2 == 2)
            oENV(k,3) = 5;
        else    % surely case (ck == 1)&(ck2 == 2) 
            oENV(k,3) = 3;
        end
        oENV(k+1,4) = 0;    % the doubled value must be deleted
    else
        oENV(k,3) = 7;
        oENV(k+1:k+2,4) = 0;
    end
end

Idel = oENV(:,4) == 0;
oENV(Idel,:) = [];
MosMom = oENV(:,[1 3]);